package cn.web.tunnelrobot;

import cn.web.tunnelrobot.dao.ProjectDao;
import cn.web.tunnelrobot.dao.ThresholdDao;
import cn.web.tunnelrobot.dao.WarningRecordDao;
import cn.web.tunnelrobot.dto.*;
import cn.web.tunnelrobot.service.UserRecordService;
import cn.web.tunnelrobot.service.impl.RealTimeDataServiceImpl;
import cn.web.tunnelrobot.util.Constants;
import cn.web.tunnelrobot.util.RealTimeDateTomcat;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * 继承Application接口后项目启动时会按照执行顺序执行run方法
 * 通过设置Order的value来指定执行的顺序
 * tomcat中调用本机项目
 * 此处废弃，这里的定时功能重新写在了StartService
 */
@Component
@Order(value = 1)
public class StartRunning implements ApplicationRunner {
    @Autowired
    private ThresholdDao thresholdDao;
    @Autowired
    private WarningRecordDao warningRecordDao;
    @Autowired
    private UserRecordService userRecordService;
    @Autowired
    private ProjectDao projectDao;
    //log4j
    Logger logger = LoggerFactory.getLogger(StartRunning.class);
    public static ProjectDTO projectDTO = new ProjectDTO();

    @Override
    public void run(ApplicationArguments args){
        /* 废弃
        //启动时给 阈值设置的ArrayList赋值
        //阈值数据按照分类拆分到各自的list
        Constants.list = thresholdDao.getThresholdList(null);
        for (Threshold threshold : Constants.list) {
            if (threshold.getThWarningSign() == 1) {
                Constants.temperature.add(threshold);
            } else if (threshold.getThWarningSign() == 2) {
                Constants.humidity.add(threshold);
            } else if (threshold.getThWarningSign() == 3) {
                Constants.oxygenConcentrations.add(threshold);
            } else if (threshold.getThWarningSign() == 4) {
                Constants.lightIntensity.add(threshold);
            } else if (threshold.getThWarningSign() == 5) {
                Constants.dustConcentration.add(threshold);
            } else if (threshold.getThWarningSign() == 6) {
                Constants.gasDensity.add(threshold);
            } else if (threshold.getThWarningSign() == 7) {
                Constants.batteryWarning.add(threshold);
            }
        }
        //创建单线程池
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        //调用硬件接口传输数据
        //实时获取硬件数据/(1:温度 2:湿度 3:氧气浓度 4:光照强度 5:粉尘浓度 6:瓦斯浓度 7:电量预警)
        // 参数：1、任务体 2、首次执行的延时时间  3、任务执行间隔 4、间隔时间单位
        service.scheduleAtFixedRate(() -> hardwareInfo(), 4, 2, TimeUnit.SECONDS);
        //监控页面获取
        service.scheduleAtFixedRate(()->  getMonitoringAddress()  ,4, 3, TimeUnit.SECONDS);
        //机器人实时位置
        service.scheduleAtFixedRate(() -> getRobotPosition(), 5, 5, TimeUnit.SECONDS);
        //垃圾回收机制
        service.scheduleAtFixedRate(() ->  System.gc(), 2, 6, TimeUnit.HOURS);
        //查询隧道语音播报位置、项目简介
        projectDTO = projectDao.getDetailProjectById(1);

         */
    }

    /**
     * 实时获取机器人位置信息
     */
    private void getRobotPosition() {
        //获取机器人实时位置信息
        try {
            String distance = Constants.doGet(RealTimeDateTomcat.robotPosition);
            //logger.info("机器人位置"+distance);
            if(StringUtils.isNotEmpty(distance)){
                if (Integer.parseInt(distance) >= 0) {
                    Integer address = Integer.parseInt(distance);
                    Constants.robotCurrentPosition = address;
                }else{
                    Constants.robotCurrentPosition = 0;
                }

            }
        } catch (Exception e) {
            logger.error("获取机器人实时位置信息报错");
//            e.printStackTrace();
        }
    }
    /**
     * 获取监控画面地址
     * 6天获取一次
     * 1：左视界面 2：上视界面 3：右视界面 4：俯视界面 5：机械臂
     * 清晰度:高清:true 标清:false
     */
    private void getMonitoringAddress() {
        try {
            String distance = Constants.doGet(RealTimeDateTomcat.realMonitoringAddress);
            List<String> list1 = Arrays.asList(distance.split(","));
            Constants.getsRealMonitoringAddress =  list1;
        } catch (Exception e) {
            logger.error("获取监控网址时发生异常");
//            e.printStackTrace();
        }
    }

    /**
     * 获取硬件传输信息进行判断
     */
    private void hardwareInfo() {
        try {
            //获取实时数据
            String realTime = Constants.doGet(RealTimeDateTomcat.realTimeData);
            HashMap hashMap = JSON.parseObject(realTime, HashMap.class);
            RealTimeData realTimeData = new RealTimeData();
            Integer csz = 0;
            //1:温度 2:湿度 3:氧气浓度 4:光照强度 5:粉尘浓度 6:瓦斯浓度 7:电量预警
            if(hashMap.get("temperature") == null){
                realTimeData.setTemperature(Float.parseFloat(String.valueOf(csz)));
            }else{
                realTimeData.setTemperature(Float.parseFloat(hashMap.get("temperature").toString()));
            }

            if(hashMap.get("humidity") == null){
                realTimeData.setHumidity(Float.parseFloat(String.valueOf(csz)));
            }else{
                realTimeData.setHumidity(Float.parseFloat(hashMap.get("temperature").toString()));
            }

            if(hashMap.get("oxygenConcentrations") == null){
                realTimeData.setOxygenConcentrations(Float.parseFloat(String.valueOf(csz)));
            }else{
                realTimeData.setOxygenConcentrations(Float.parseFloat(hashMap.get("oxygenConcentrations").toString()));
            }

            if(hashMap.get("lightIntensity") == null){
                realTimeData.setLightIntensity(Float.parseFloat(String.valueOf(csz)));
            }else{
                realTimeData.setLightIntensity(Float.parseFloat(hashMap.get("lightIntensity").toString()));
            }

            if(hashMap.get("lightIntensity") == null){
                realTimeData.setDustConcentration(Float.parseFloat(String.valueOf(csz)));
            }else{
                realTimeData.setDustConcentration(Float.parseFloat(hashMap.get("dustConcentration").toString()));
            }

            if(hashMap.get("gasDensity") == null){
                realTimeData.setGasDensity(Float.parseFloat(String.valueOf(csz)));
            }else{
                realTimeData.setGasDensity(Float.parseFloat(hashMap.get("gasDensity").toString()));
            }

            if(hashMap.get("batteryWarning") == null){
                realTimeData.setBatteryWarning(Integer.parseInt(String.valueOf(csz)));
            }else{
                realTimeData.setBatteryWarning(Integer.parseInt(hashMap.get("batteryWarning").toString()));
            }

            if(hashMap.get("spareBatteryWarning") == null){
                realTimeData.setSpareBatteryWarning(Integer.parseInt(String.valueOf(csz)));
            }else{
                realTimeData.setSpareBatteryWarning(Integer.parseInt(hashMap.get("spareBatteryWarning").toString()));
            }
            Constants.realTimeData = realTimeData;
            //获取警告数据
            String warningData = Constants.doGet(RealTimeDateTomcat.warningList);
            //logger.info("warningData:"+warningData);
            if(!warningData.equals("[]")){
                List<Warning> warningList = new ArrayList<>();
                List<String> list = Arrays.asList(warningData.split("},"));
                //logger.info("listS:"+list.size());
                int i = 0;
                for (String abc:list){
                    //logger.info(i+"原始:"+abc);
                    if(i==0){
                        abc = abc.substring(1) + "}";
                        i++;
                    }else if(i==(list.size()-1)){
                        abc =  abc.substring(0,abc.length()-1);
                        i++;
                    }else{
                        abc = abc  + "}";
                        i++;
                    }
                    HashMap hashMap1 = JSON.parseObject(abc, HashMap.class);
                   /* logger.info(hashMap1.get("code").toString());
                    logger.info(hashMap1.get("level").toString());
                    logger.info(hashMap1.get("msg").toString());*/
                    Warning warning = new Warning();
                    warning.setId(Integer.parseInt(hashMap1.get("id").toString()));
                    warning.setCode(Integer.parseInt(hashMap1.get("code").toString()));
                    warning.setLevel(hashMap1.get("level").toString());
                    warning.setMsg(hashMap1.get("msg").toString());
                    warningList.add(warning);
                }
                Constants.warningList = warningList;
                //logger.info(""+Constants.warningList.size());
            }else{
                //logger.info("硬件信息是空的");
            }
        } catch (Exception e) {
            logger.error("硬件采集信息时发生异常!");
//            e.printStackTrace();
        }
    }
}
